<template>
  <a-card>
    <div style="display: flex; justify-content: flex-end; margin-bottom: 20px">
      <div style="margin-right: 60px">
        <a-input-search
          :placeholder="$t('user.verification-code.required111566172')"
          style="width: 200px; margin-left: 40px"
          @search="onSearch"
          v-model="searchInfo"
          @change="changeinout"
        />
      </div>
      <a-button
        type="primary"
        html-type="submit"
        icon="plus"
        @click="showModal('add')"
        >{{ $t("user.verification-code.required11156611052") }}
      </a-button>
    </div>
    <a-table
      ref="table"
      size="middle"
      class="h-full overflow-x-auto"
      :dataSource="listData"
      @change="tableChange"
      :pagination="false"
      :rowKey="
        (record, index) => {
          return record.Id;
        }
      "
    >
      <a-table-column key="ActionId" data-index="ActionId">
        <span slot="title" class="min-w-90p">合规要求编号</span>
      </a-table-column>
      <a-table-column key="ActionName" data-index="ActionName">
        <span slot="title" class="min-w-90p">{{
          $t("user.verification-code.required1115661105711")
        }}</span>
      </a-table-column>
      <a-table-column
        key="ActionType"
        data-index="ActionType"
        :title="$t('user.verification-code.required111566110577128')"
      >
      </a-table-column>
      <a-table-column key="ActionCreateUser" data-index="ActionCreateUser">
        <span slot="title" class="min-w-90p">{{
          $t("user.verification-code.required1115661105793")
        }}</span>
      </a-table-column>
      <a-table-column key="ActionCreatetime" data-index="ActionCreatetime">
        <span slot="title" class="min-w-90p">{{
          $t("user.verification-code.required111566131")
        }}</span>
      </a-table-column>
      <a-table-column key="ActionUpdatetime" data-index="ActionUpdatetime">
        <span slot="title" class="min-w-90p">{{
          $t("user.verification-code.required1115661105794")
        }}</span>
      </a-table-column>
      <a-table-column key="action" :title="$t('menu.exception.not-find')">
        <template slot-scope="text, record">
          <span>
            <a-button type="link" @click="showModal('edit', record.Id)">{{
              $t("user.verification-code.required111566147")
            }}</a-button>
            <a-popconfirm
              :title="$t('user.verification-code.required111566110577225')"
              :ok-text="$t('user.verification-code.required1166')"
              :cancel-text="$t('user.email.required11')"
              @confirm="del(record.Id)"
            >
              <a-button type="link">{{ $t("app.setting.copy") }}</a-button>
            </a-popconfirm>
          </span>
        </template>
      </a-table-column>
    </a-table>

    <a-pagination
      size="small"
      v-model="pagination.page"
      :total="pagination.total"
      hideOnSinglePage
      :pageSize.sync="pagination.pageSize"
      @change="getList"
    />

    <!-- 添加，修改  -->
    <a-drawer
      :title="modalTitle"
      placement="right"
      :closable="false"
      :visible="modalVisible"
      @close="closeDrawer"
      :width="500"
    >
      <a-form
        :form="form"
        labelAlign="right"
        style="margin-top: -20px; padding-bottom: 100px"
      >
        <a-form-item label="ID" v-show="false" class="hidden">
          <a-input v-decorator="['Id']" disabled />
        </a-form-item>
        <a-form-item label="ActionID：">
          <a-input
            v-decorator="['ActionId']"
            placeholder="合规要求编号"
            disabled
          />
        </a-form-item>
        <a-form-item
          :label="$t('user.verification-code.required111566110577128')"
        >
          <a-select
            v-decorator="[
              'ActionType',
              {
                rules: [
                  {
                    required: true,
                    message: $t(
                      'user.verification-code.required111566110577323'
                    ),
                  },
                ],
              },
            ]"
            option-filter-prop="children"
            :filter-option="filterOption"
            show-search
            :placeholder="$t('user.verification-code.required111566110577128')"
          >
            <a-select-option
              v-for="item in selectList"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label="$t('user.verification-code.required1115661105711')"
        >
          <a-input
            v-decorator="[
              'ActionName',
              {
                rules: [
                  {
                    required: true,
                    message: $t(
                      'user.verification-code.required111566110577324'
                    ),
                  },
                ],
              },
            ]"
            :placeholder="$t('user.verification-code.required1115661105711')"
          />
        </a-form-item>
        <a-form-item
          :label="$t('user.verification-code.required111566110571111')"
        >
          <a-input-number
            v-decorator="[
              'ActionWeight',
              {
                rules: [
                  {
                    required: true,
                    message: $t(
                      'user.verification-code.required11156611057732444'
                    ),
                  },
                ],
              },
            ]"
            :placeholder="$t('user.verification-code.required111566110571111')"
            style="width: 100%"
            :min="0"
            :precision="0"
          />
        </a-form-item>
        <a-form-item
          style="margin: 0"
          :label="$t('user.verification-code.required111566173')"
        >
          <a-textarea
            :auto-size="{ minRows: 3, maxRows: 10 }"
            :placeholder="$t('user.verification-code.required111566173')"
            :rows="3"
            v-decorator="['ActionInfo']"
            style="width: 615px"
          />
        </a-form-item>
        <!-- 备注的timeline -->
        <a-form-item label="法律法规详细来源">
          <a-timeline>
            <a-timeline-item v-for="(item, index) in inputList" :key="item.id">
              <!-- 操作按钮 -->
              <a-space size="0" align="center">
                <p style="min-width: 150px">
                  {{ item.actionCreateUser }} {{ item.actionCreateTime }}
                </p>
                <a-button
                  v-if="item.editable === false"
                  type="link"
                  @click="editInput(item, index)"
                  >{{ $t("user.verification-code.required111566147") }}
                </a-button>
                <a-button
                  v-if="item.editable === true"
                  type="link"
                  @click="okInput(item, index)"
                  >{{ $t("user.verification-code.required1166") }}
                </a-button>
                <a-button type="link" @click="deleteInput(item)">{{
                  $t("app.setting.copy")
                }}</a-button>
              </a-space>
              <a-form-item>
                <a-textarea
                  :auto-size="{ minRows: 3, maxRows: 10 }"
                  :placeholder="$t('user.verification-code.required111566181')"
                  :rows="3"
                  :disabled="!item.editable"
                  v-model="item.value"
                />
              </a-form-item>
            </a-timeline-item>
            <!-- 备注的新增 -->
            <a-button style="float: right" @click="addInput"
              >{{ $t("user.verification-code.required1115661814455") }}
            </a-button>
          </a-timeline>
        </a-form-item>
        <a-form-item
          :label="$t('user.verification-code.required111566180234')"
          style="margin-top: -10px"
        >
          <a-textarea
            :auto-size="{ minRows: 3, maxRows: 10 }"
            :placeholder="
              $t('user.verification-code.required11156618011667788')
            "
            :rows="3"
            v-decorator="[
              'ActionResult',
              {
                rules: [
                  {
                    message: $t(
                      'user.verification-code.required111566110577325'
                    ),
                  },
                ],
              },
            ]"
            style="width: 615px"
          />
        </a-form-item>
        <!-- 上传提交 -->
        <a-upload
          :multiple="true"
          :file-list="fileLists"
          :customRequest="handleChange"
          :remove="delFile"
        >
          <a-button v-show="current === 0">
            <a-icon type="upload" />
                落地要求示例和验收标准示例
          </a-button>
        </a-upload>
      </a-form>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'center',
          zIndex: 1,
        }"
      >
        <a-button style="margin-right: 8px" @click="closeDrawer">{{
          $t("user.email.required11")
        }}</a-button>
        <a-button type="primary" @click="createAction">{{
          $t("user.verification-code.required1166")
        }}</a-button>
      </div>
    </a-drawer>
  </a-card>
</template>

<script>
import { userQuery } from "@/api/common/form";
import {
  dpiaActionBeizhuDelete,
  dpiaActionBeizhuUpdate,
  dpiaActionModelChange,
  dpiaActionModelCreate,
  dpiaActionModelDelete,
  dpiaActionModelDetail,
  dpiaActionModelLists,
} from "@/api/dpia/form";

import { dpiaActionBeizhuadd } from "@/api/dpia/json";
import axios from "axios";
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";

const columns = [
  {
    title: "Action模板ID",
    className: "min-w-90p",
    dataIndex: "ActionId", //名称
    align: "center",
  },
  {
    title: "合规要求名称",
    className: "min-w-90p",
    dataIndex: "ActionName",
    align: "center",
  },

  {
    title: "合规要求来源",
    className: "min-w-90p",
    dataIndex: "ActionDcoChoice",
    scopedSlots: { customRender: "actionDcoChoice" },
    align: "center",
  },
  {
    title: "创建人",
    className: "min-w-90p",
    dataIndex: "ActionCreateUser",
    align: "center",
  },
  {
    title: "创建时间",
    className: "min-w-90p",
    dataIndex: "ActionCreatetime",
    align: "center",
  },
  {
    title: "最后更新时间",
    className: "min-w-90p",
    dataIndex: "ActionUpdatetime",
    align: "center",
  },
  {
    title: "操作",
    width: "280px",
    dataIndex: "",
    align: "center",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  created() {
    this.init();
  },
  data() {
    return {
      fileLists: [],
      id: "",
      urlList11: [],
      listLoading: false,
      current: 0,
      actionId: "",
      idadd: 0,
      //存上传文件接口地址
      urlList: [],
      env: process.env.VUE_APP_BASE_API,
      childrenDrawer: false,
      form: this.$form.createForm(this),
      columns: columns,
      listData: [],
      modalTitle: "",
      modalVisible: false,
      confirmLoading: false,
      // 备注列表
      inputList: [],
      modestate: 0,
      type: "",
      // 当前用户信息
      ActionCreateUserName: this.$store.state.user.info.name,
      ActionCreateUser: "",
      actionname: "",
      actiontime: "",
      userList: [],
      edit: "",
      remark: {},
      okType: "",
      pagination: {
        page: 1, //当前页
        pageSize: 10, //每页条数
        total: 0, //总条数
        showQuickJumper: true,
        hideOnSinglePage: true,
      },
      selectList: [
        {
          value: 1,
          label: "DPIA安全要求",
        },
        {
          value: 2,
          label: "数据泄露措施",
        },
        {
          value: 3,
          label: "手动创建",
        },
      ],
      searchInfo: "",
    };
  },
  methods: {
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    tableChange() {},
    async init() {
      console.log("this.iddadd", this.idadd);
      console.log("this.mode", this.modestate);
      this.getList();
    },
    async getList() {
      await this.$nextTick();
      this.listLoading = true;
      const { page, pageSize } = this.pagination;
      if (this.inputList.length < 1) {
        this.inputList.push({
          id: 1,
          value: "",
          editable: true,
        });
      }
      try {
        // 调用查询列表
        // 获取用户列表下拉
        const { data: userList } = await userQuery(1);
        this.userList = userList;
        const { data } = await dpiaActionModelLists({
          ...{ page, pageSize },
          ...this.queryForm,
          ActionName: this.searchInfo,
        });
        // 解构赋值
        const { Page, PageSize, Total, Lists } = data;
        console.log("Lists-----------------", Lists);
        // 给table赋值
        this.listData = Lists || [];

        // 给分页数据赋值
        this.pagination = {
          page: Page,
          pageSize: PageSize,
          total: Total,
        };
      } catch (error) {
        // 报错信息
        this.$message.error(error);
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false;
      }
    },
    changeinout(value) {
      console.log(value.data);
      if (value.data == null) {
        this.pagination.page = 1;
        this.getList();
      }
    },
    async onSearch(value) {
      console.log(value);
      this.listLoading = true;
      this.pagination.page = 1;
      const { page, pageSize } = this.pagination;
      try {
        const { data: userList } = await userQuery(1);
        this.userList = userList;
        const { data } = await dpiaActionModelLists({
          ...{ page, pageSize },
          ...{ ActionName: value },
        });
        // 解构赋值
        const { Page, PageSize, Total, Lists } = data;
        console.log("Lists-----------------", Lists);
        // 给table赋值
        this.listData = Lists || [];

        // 给分页数据赋值
        this.pagination = {
          page: Page,
          pageSize: PageSize,
          total: Total,
        };
      } catch (error) {
        // 报错信息
        this.$message.error(error);
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false;
      }
    },
    //子抽屉展示
    async openAction(actionId, data) {
      if (this.inputList.length < 1) {
        this.inputList.push({
          id: 1,
          value: "",
          editable: true,
        });
      }

      this.childrenDrawer = true;
      this.actionId = actionId;
      this.id = id;
      if (!data) {
        await this.$nextTick();
        this.form.setFieldsValue({
          ActionId: actionId,
        });
      } else {
        await this.$nextTick();
        this.form.setFieldsValue({
          ActionId: data.ActionId,
          ActionName: data.ActionName,
          ActionInfo: data.ActionInfo,
          ActionResult: data.ActionResult,
          ActionType: data.ActionType,
          ActionCreatetim: data.ActionCreatetim,
          ActionCreateUserName: data.ActionCreateUserName,
        });
      }
    },
    //子抽屉关闭
    onChildrenDrawerClose() {
      this.inputList = [];
      this.childrenDrawer = false;
      this.fileLists - [];
      this.$emit("getList");
    },
    // 编辑Action
    async editAction(id) {
      const { data } = await dpiaActionModelDetail({ Id: id });
      await this.$nextTick();
      this.form.setFieldsValue({
        ActionCreateUser: data.ActionCreateUser,
        ActionId: data.ActionId,
        ActionInfo: data.ActionInfo,
        ActionName: data.ActionName,
        ActionType: data.ActionType,
        ActionResult: data.ActionResult,
        ActionCreatetim: data.ActionCreatetim,
        ActionCreateUserName: data.ActionCreateUserName,
      });
    },
    // 添加，修改
    async showModal(type, id) {
      this.form.resetFields();
      this.type = type;
      if (type == "edit") {
        //编辑
        this.modalVisible = true;
        await this.$nextTick();
        this.modalTitle = this.$t(
          "user.verification-code.required111566110577163"
        );
        const { data } = await dpiaActionModelDetail({ Id: id });
        this.actionId = data.ActionId;
        this.id = data.Id;

        // 赋值
        this.form.setFieldsValue({
          ActionId: data.ActionId,
          Id: data.Id,
          ActionCreateUser: data.ActionCreateUser,
          ActionInfo: data.ActionInfo,
          ActionName: data.ActionName,
          ActionType: data.ActionType,
          ActionResult: data.ActionResult,
          ActionCreateUserName: data.ActionCreateUserName,
          ActionWeight: data.ActionWeight,
        });

        // 赋予内容
        // this.ActionCreateUserName = data.ActionCreateUserInfo
        // this.ActionCreateUser = data.ActionCreateUser

        // 初始化数据
        this.inputList = [];
        this.fileLists = [];
        var index = this.fileLists.length;
        // 赋值
        if (data.Info != null && data.Info != undefined) {
          for (var i = 0; i < data.Info.length; i++) {
            if (parseInt(data.Info[i].ActionType) == 1) {
              this.inputList.push({
                Id: data.Info[i].Id,
                value: data.Info[i].ActionRemarkInfo,
                editable: false,
                actionCreateTime: data.Info[i].ActionCreatetime,
                actionCreateUser: data.Info[i].ActionCreateUserInfo,
                actionCreateUserId: data.Info[i].ActionCreateUser,
              });
            } else {
              console.log(data.Info);
              var fileName = data.Info[i].ActionUploadUrl.split("/");
              this.fileLists.push({
                uid: index + 1,
                name: fileName[fileName.length - 1],
                status: "done",
                url: data.Info[i].ActionUploadUrl,
                Id: data.Info[i].Id,
              });
            }
          }
        }

        // 如果备注一个都没有就初始化一个
        if (this.inputList.length < 1) {
          this.addInput();
        }
      } else {
        this.modalVisible = true;
        this.idadd = 1;
        console.log("this.idd", this.idadd);
        this.fileLists = [];
        this.inputList = [];
        await this.$nextTick();
        this.modalTitle = this.$t(
          "user.verification-code.required111566110577162"
        );
        const { data } = await dpiaActionModelCreate();
        // 赋值
        this.actionId = data.ActionId;
        this.id = data.Id;

        // 保留创建时间、创建人信息
        var actionCreateTime = data.ActionCreatetime;
        var actionCreateUser = data.ActionCreateUserName;
        var actionCreateUserId = data.ActionCreateUser;
        this.form.setFieldsValue({
          ActionId: data.ActionId,
          Id: data.Id,
          ActionCreateUserName: data.ActionCreateUserName,
          ActionCreateUser: data.ActionCreateUser,
        });

        // 赋予内容
        this.ActionCreateUserName = data.ActionCreateUserName;
        this.ActionCreateUser = data.ActionCreateUser;

        // 创建备注列表初始化
        this.inputList.push({
          value: "",
          editable: true,
          actionCreateTime: actionCreateTime,
          actionCreateUser: actionCreateUser,
          actionCreateUserId: actionCreateUserId,
        });
      }
    },
    // 点击新增按钮中弹框的确定按钮
    async createAction() {
      this.modestate = 1;
      console.log("this.modestate", this.modestate);
      const {
        form: { validateFields },
      } = this;
      // 按钮loading
      this.loading = true;
      validateFields({ force: true }, async (err, values) => {
        if (!err) {
          try {
            const { data: actionInfos } = await dpiaActionModelChange({
              ...values,
            });

            for (var i = 0; i < this.fileLists.length; i++) {
              let arr = [];
              arr = this.fileLists[i].url.split("/").splice(-2, 2);
              await dpiaActionBeizhuadd([
                {
                  ActionId: actionInfos.Id,
                  ActionType: 2,
                  ActionUploadUrl: arr.join("/"),
                },
              ]);
            }
            if (this.type == "edit") {
              this.$message.success(
                this.$t("user.verification-code.required111566110577229")
              );
            } else {
              this.$message.success(
                this.$t("user.verification-code.required111566110577230")
              );
            }

            this.closeDrawer();
          } catch (error) {
            this.$message.error(error);
          } finally {
            this.loading = false;
          }
          this.getList();
        } else {
          setTimeout(() => {
            this.loading = false;
          }, 600);
        }
      });
    },

    // 关闭抽屉
    async closeDrawer() {
      console.log("this.iddadd", this.idadd);
      console.log("this.mode", this.modestate);
      this.modalVisible = false;
      this.addAppForm = {};
      if (this.idadd == 1 && this.modestate == 0) {
        // 传过来的id直接请求删除api
        await dpiaActionModelDelete({ Id: this.id });
        console.log("2233");
        // 重新初始化列表刷新数据
        this.getList();
        this.form.resetFields();
        this.urlList = [];
        this.modestate = 0;
        this.idadd = 0;
      } else {
        this.addAppForm = {};
        this.modalVisible = false;
        this.form.resetFields();
        this.urlList = [];
        this.modestate = 0;
        this.idadd = 0;
      }
    },
    // 上传提交
    async handleChange(e) {
      this.uploadLoading = true;
      let formdata = new FormData();
      formdata.append("file", e.file);
      try {
        const { status, data } = await axios({
          url: `${this.env}/v1/oss/upload`,
          method: "post",
          data: formdata,
          headers: {
            token: storage.get(ACCESS_TOKEN),
            tokens: storage.get("bmwToken") || "",
          },
        });
        if (status == 200 && data.code == 1) {
          if (data.data != "") {
            await this.$nextTick();
            var files = data.data;
            var index = this.fileLists.length;
            if (files != "" && files != undefined) {
              var fileName = files.split("/");
              this.fileLists.push({
                uid: index + 1,
                name: fileName[fileName.length - 1],
                status: "done",
                url: data.Url + data.data,
              });
            }
          } else {
            this.showModal();
          }
        } else {
          this.$message.error(
            this.$t("user.verification-code.required111566110577282")
          );
        }
      } catch (error) {
        console.log(error);
        this.$message.error(error);
      } finally {
        this.uploadLoading = false;
      }
    },
    // 添加
    addInput() {
      var objData = new Date();
      var year = objData.getFullYear();
      var month = objData.getMonth() + 1;
      var day = objData.getDate();
      if (objData.getSeconds() < 10) {
        var seconds = "0" + objData.getSeconds();
      } else {
        var seconds = objData.getSeconds();
      }
      if (objData.getMinutes() < 10) {
        var miuntes = "0" + objData.getMinutes();
      } else {
        var miuntes = objData.getMinutes();
      }
      if (objData.getHours() < 10) {
        var hours = "0" + objData.getHours();
      } else {
        var hours = objData.getHours();
      }
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      // 新增一个新的数据初始化
      this.inputList.push({
        value: "",
        editable: true,
        actionCreateTime:
          year +
          "-" +
          month +
          "-" +
          day +
          " " +
          hours +
          ":" +
          miuntes +
          ":" +
          seconds,
        actionCreateUser: this.ActionCreateUserName,
        actionCreateUserId: this.ActionCreateUser,
      });
    },
    //编辑
    async editInput(item, index) {
      item.editable = true;
    },
    //备注确认
    async okInput(item, index1) {
      // 修改状态为不可编辑
      item.editable = false;
      if (Object.keys(item).indexOf("Id") != -1) {
        // 更新
        const { data } = await dpiaActionBeizhuUpdate({
          Id: item.Id,
          ActionRemarkInfo: item.value,
          ActionId: this.id,
          ActionType: 1,
        });
        item.actionCreateTime = data.ActionUpdatetime;
      } else {
        // 新增
        const { data } = await dpiaActionBeizhuadd([
          {
            ActionRemarkInfo: item.value,
            ActionId: this.id,
            ActionType: 1,
          },
        ]);
        // 赋值
        item.Id = data.Id;
        item.actionCreateTime = data.ActionCreatetime;
      }
    },
    //删除
    async deleteInput(item) {
      await dpiaActionBeizhuDelete({ Id: item.Id });
      const index = this.inputList.indexOf(item);
      this.inputList.splice(index, 1);
    },
    /**
     * 删除
     * @param {} id
     */
    async del(id) {
      await this.$nextTick();
      try {
        // 传过来的id直接请求删除api
        await dpiaActionModelDelete({ Id: id });
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
        // 重新初始化列表刷新数据
        this.getList();
      } catch (error) {
        this.$message.error(error);
      } finally {
      }
    },
    async delFile(file) {
      const index = this.fileLists.indexOf(file);
      this.fileLists.splice(index, 1);
      await dpiaActionBeizhuDelete({ Id: file.Id });
      return true;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .ant-drawer-body {
  height: 800px !important;
}

.ant-pagination {
  float: right;
}

/deep/ .ant-timeline-item-content {
  top: -11px;
}

/deep/ .ant-timeline-item {
  padding: 0 0 1px;
}

/deep/ .ant-form-item {
  margin-bottom: 0px;
}

/deep/ .ant-space-align-center {
  align-items: center;
  margin-left: 230px;
}

/deep/ .ant-space-align-center {
  align-items: center;
  margin-left: 0 !important;
}
</style>
